# -*- coding:utf-8 -*-
import bluetooth
import prettytable as pt
BT_PRPOTOCOL = {1:'SDP', 2:'UDP', 3:'RFCOMM', 4:'TCP', 5:'TCS_BIN', 6:'TCS_AT', 8:'OBEX', 9:'IP', 10:'FTP', 12:'HTTP',
                14:'WSP', 15:'BNEP', 16:'UPNP', 17:'HIDP', 18:'HCRP_CTRL', 20:'HCRP_DATA', 22:'HCRP_NOTE', 23:'AVCTP',
                25:'AVDTP', 27:'CMTP', 29:'UDI', 31:'L2CAP'}

def l2capCon(addr, psm):
    sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    try:
        sock.connect((addr,psm))
        sock.close()
        return 1
    except Exception,e:
        return 0
def ble_device_type(device_type):
    if device_type == 'S9P' or device_type == 'Mi Band 3':
        return 'Band'
    return 'unknown'

def bt_device_type(device_type):
    if device_type == 5898764 or device_type == 'Android':
        return 'Android'
    if device_type == 7078144 or device_type == 'computer_ubuntu14':
        return 'computer_ubuntu14'
    if device_type == 786700 or device_type == 'computer_ubuntu16':
        return 'computer_ubuntu16'
    if device_type == 655620 or device_type == 'computer_windows':
        return 'computer_windows'
    if device_type == 2360324 or device_type == 'headset':
        return 'headset'
    if device_type == 2360328 or device_type =='speaker':
        return 'speaker'
    if device_type == 263208 or device_type == 'SV':
        return 'SV'
    if device_type == 7995916 or device_type == 'phone':
        return 'phone'
    if device_type == 3670284 or device_type == 'MACBook':
        return 'MACBook'
    if device_type == 7936 or device_type == 2752780 or device_type == 'PC':
        return 'PC'
    if device_type == 6947088 or device_type == 'iPad':
        return 'iPad'
    return 'unknown'


# service scan
def bt_device_service(addr, name, device_type):
     if len(addr) == 17:
        services = bluetooth.find_service(address=addr)
        for svc in services:
           #  status = "on"

            '''print("Service Name: %s" % svc["name"])
            print("    Host:        %s" % svc["host"])
            print("    Description: %s" % svc["description"])
            print("    Provided By: %s" % svc["provider"])
            print("    Protocol:    %s" % svc["protocol"])
            print("    channel/PSM: %s" % svc["port"])
            print("    svc classes: %s " % svc["service-classes"])
            print("    profiles:    %s " % svc["profiles"])
            print("    service id:  %s " % svc["service-id"])
            print("")'''
            # protocol scan
            pro = []
            device_type_name = bt_device_type(device_type)
            if(device_type_name == "phone" or device_type_name == "MACBook" or device_type_name == "iPad"):
                pro.append(BT_PRPOTOCOL[1])     #Apple Devides Only Open Port 1 Before Connect
                svc['pro']=pro
            else:
                for port in range(2, 31):
                    if l2capCon(addr, port):
                        pro.append(BT_PRPOTOCOL[port])
                svc['pro'] = pro
            return svc
        '''
        pro = []
        for port in range(1, 31):
            if l2capCon(addr, port):
                pro.append(BT_PRPOTOCOL[port])
        print "the bt device has those protocol:"'''
        # print pro
        #print tb2
     else:
         print "please enter valid MAC"

if __name__ == '__main__':
    # device scan
    while True:
        #print("looking for nearby devices...")
        nearby_devices = bluetooth.discover_devices(lookup_names=True, lookup_class=True)
        #print nearby_devices
        tb2 = pt.PrettyTable()
        tb2.field_names = ["MAC", "设备名称", "设备类型", "服务名称", "   主机", "  描述", "生产厂商", "  协议", "  端口", "服务类型", "配置",
                           "Service_id", "pro", "在线"]
        for addr, name, device_type in nearby_devices:
            status ='on'
            svc = bt_device_service(str(addr), name, device_type)
            tb2.add_row(
                [addr, name, bt_device_type(device_type), svc["name"], svc["host"], svc["description"], svc["provider"],
                 svc["protocol"], svc["port"], svc["service-classes"],
                 svc["profiles"], svc["service-id"], svc['pro'], status])
            #print '%s %s %s' %(addr, name, bt_device_type(device_type))
            #bt_device_service(str(addr), name, device_type)
        print tb2
        # the addr you want to scan
        '''addr = raw_input('please input the MAC:')
        bt_device_service(str(addr))
        '''
